<template>
	<el-card class="box-card">
		<el-form :model="formData" ref="formData">
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">活动添加</el-col>
			</el-form-item>
			<el-form-item prop="courseName">
				<el-input v-model="formData.courseName" placeholder="输入活动全称，最少8个字，最少50个字" style="width:65%"></el-input>
			</el-form-item>
			<el-form-item prop="courseType">
				<el-select v-model="formData.courseType" placeholder="选择所属分类">
					<el-option v-for="item in classifyList" :key="item.id" :label="item.value" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">基本信息</el-col>
			</el-form-item>
			<el-row>
				<el-col :span="4">
					<el-select v-model="formData.courseOwner" placeholder="选择商户">
						<el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="8">
					商户提点：{{customer.takePercent}}%，相当于{{ldRmb}}元
				</el-col>
			</el-row>
			<el-row>提示：以下信息根据选择商户显示，此界面不可编辑，如果更新商户信息，请到商户列表操作</el-row>
			<el-row>
				<div id="allmap"></div>
			</el-row>
			<el-row style="line-height: 40px;margin-top: 10px;">
				<el-col :span="17" style="background-color: #e6e6e6;padding-left: 10px;">地址:{{customer.customerAddress}}</el-col>
				<el-col :span="6" style="margin-left: 10px;background-color: #e6e6e6;padding-left: 10px;width:28.3%">{{customer.linkerPhone}}</el-col>
			</el-row>
			<el-form-item prop="coursePoints" style="margin-top: 20px;">
				<el-input @change="changeValue" v-model="formData.coursePoints" placeholder="输入遛点" style="width:65%"></el-input>
				<span>提示:1遛点={{ld.value}}元，相当于{{rmb}}元</span>
			</el-form-item>
			<el-form-item prop="marketPrice">
				<el-input @change="changePer" v-model="formData.marketPrice" placeholder="输入市场价" style="width:65%"></el-input>
				<span>折扣:{{per}}%</span>
			</el-form-item>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">详细信息</el-col>
			</el-form-item>
			<ul class="el-upload-list el-upload-list--picture-card" style="float: left;" v-show="hasLicenceImg">
				<li class="el-upload-list__item is-success" v-for="item in courseImg">
					<img :src="item" alt="" class="el-upload-list__item-thumbnail">
					<i class="el-icon-close"></i>
					<span class="el-upload-list__item-actions" @click="haslicenceImgsRemove(item)">
						<span class="el-upload-list__item-delete"><i class="el-icon-delete2"></i></span>
					</span>
				</li>
			</ul>
			<el-upload class="avatar-uploader" :action="uploadUrl" :before-upload="beforeUpload" list-type="picture-card" :on-success="licenceImgsPreview" :on-remove="licenceImgsRemove">
				<i class="el-icon-plus"></i>
			</el-upload>
			<el-dialog v-model="licenceImgsVisible" size="tiny">
				<img width="100%" :src="courseImgsUrl" alt="">
			</el-dialog>
			<span>提示:图片尺寸200*120最佳，最多6张图</span>
			<el-form-item>
				<el-input v-model="formData.maxBabys" placeholder="课程人数" style="width:25%"></el-input>
				<el-input v-model="formData.courseDuration" placeholder="课程时长" style="width:25%"></el-input>
			</el-form-item>
			<el-form-item label="课程适用宝宝年龄" prop="shName">
				<el-input v-model="formData.minAge" placeholder="宝宝年龄" style="width:25%"></el-input>-
				<el-input v-model="formData.maxAge" placeholder="宝宝年龄" style="width:25%"></el-input>
			</el-form-item>
			<el-form-item prop="courseBrief">
				<el-input type="textarea" :rows="5" placeholder="请输入课程简介" v-model="formData.courseBrief">
				</el-input>
			</el-form-item>
			<el-form-item prop="arriveTime">
				<el-select v-model="formData.arriveTime" placeholder="选择到场时间">
					<el-option v-for="item in arriveTimeList" :key="item" :label="item" :value="item">
					</el-option>
				</el-select>
				<el-select v-model="formData.isCancel" placeholder="选择取消课程许可">
					<el-option v-for="item in cancelList" :key="item.id" :label="item.value" :value="item.id">
					</el-option>
				</el-select>
				<el-switch v-model="formData.needParents" on-color="#13ce66" off-color="#ff4949" on-value="1" off-value="0">
				</el-switch>是否需要陪护
			</el-form-item>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">时间信息</el-col>
			</el-form-item>
			<el-form-item>
				<el-row>
					<ul class="el-upload-list el-upload-list--picture-card" style="float: left;">
						<li class="el-upload-list__item is-success" v-for="item in formData.courseTimes">
							<span class="selDate">{{item.startTime}}</span>
							<i class="el-icon-close"></i>
							<span class="el-upload-list__item-actions" @click="removeDate(item)">
						<span class="el-upload-list__item-delete"><i class="el-icon-delete2"></i></span>
							</span>
						</li>
					</ul>
				</el-row>
				<el-row>
					<el-col>
						<el-date-picker v-model="subTime.startTime" type="date" placeholder="选择日期时间"></el-date-picker>
					</el-col>
					<el-col>
						<el-input v-model="subTime.coursePoint" placeholder="请输入遛点" style="width:194px">
						</el-input>
					</el-col>
					<el-col>
						<el-input v-model="subTime.maxBabys" placeholder="请输入名额" style="width:194px">
						</el-input>
					</el-col>
					<el-button type="info" style="width:194px;margin-top: 10px;" @click="addSubTime">添加</el-button>
				</el-row>
			</el-form-item>
			<el-form-item label="体验课次数" prop="tasteTimes">
				<el-input v-model="formData.tasteTimes" placeholder="请输入体验课次数" style="width:65%">
				</el-input>
			</el-form-item>
			<el-form-item label="体验课价格" prop="tastePrice">
				<el-input v-model="formData.tastePrice" placeholder="请输入体验课价格" style="width:65%">
				</el-input>
			</el-form-item>
			<el-form-item label="报名开启时间" prop="enterStartTime">
				<el-input v-model="formData.enterStartTime" placeholder="报名开启时间" style="width:65%">
				</el-input>
			</el-form-item>
			<el-form-item label="报名截止日期" prop="enterEndTime">
				<el-input v-model="formData.enterEndTime" placeholder="报名截止日期" style="width:65%">
				</el-input>
			</el-form-item>
			<el-form-item class="title" label-width="30px">
				<el-col :span="16">其他信息</el-col>
			</el-form-item>
			<el-form-item prop="memo">
				<el-input type="textarea" :rows="5" placeholder="其他小编提示" v-model="formData.memo">
				</el-input>
			</el-form-item>
			<el-form-item label="选择赠送项目" prop="presentItems">
				<el-checkbox-group v-model="presentItems">
					<el-checkbox label="停车"></el-checkbox>
					<el-checkbox label="洗浴"></el-checkbox>
					<el-checkbox label="餐点"></el-checkbox>
					<el-checkbox label="照片"></el-checkbox>
				</el-checkbox-group>
			</el-form-item>
		</el-form>
		<el-button type="info" style="width:100%;margin-top: 10px;" @click="courseSaveFun('formData')">确认提交</el-button>
	</el-card>
</template>

<script>
	import { courseSave, courseUpdate, courseInfo, upload, customerList, metaList } from "@/api/getData"
	import dtime from 'time-formater'
	export default {
		data() {
			return {
				licenceImgsVisible: false,
				hasLicenceImg: false,
				formData: {
					courseName: "",
					enterStartTime: "",
					enterEndTime: "",
					courseType: "",
					courseOwner: "",
					coursePoints: "",
					maxBabys: "",
					courseDuration: "",
					maxAge: "",
					minAge: "",
					arriveTime: "",
					isCancel: "",
					needParents: "",
					tasteTimes: "",
					tastePrice: "",
					courseImgs: "",
					marketPrice: "",
					courseTimes: [],
					presentItems: "",
					id: "",
				},
				customer: {

				},
				subTime:{
					coursePoint:"",
					startTime:"",
					maxBabys:"",
				},
				etrName: "",
				names: [],
				local: null,
				map: null,
				courseImg: [],
				customerList: [],
				presentItems: [],
				courseImgsUrl: "",
				classifyList: [],
				uploadUrl: "",
				ld: {},
				ldRmb: "",
				rmb: "",
				per: "0",
				arriveTimeList: ["按时到即可", "提前10分钟", "提前30分钟", "提前1小时", "提前2小时"],
				cancelList: [{
						id: 0,
						value: "不可取消"
					},
					{
						id: 24,
						value: "课程开始前24小时"
					},
					{
						id: 48,
						value: "课程开始前48小时"
					},
				]
			}
		},
		mounted() {
			let _this = this;
			// 百度地图API功能
			_this.map = new BMap.Map("allmap"); // 创建地图实例
			let point = new BMap.Point(116.404, 39.915);
			_this.map.centerAndZoom(point, 15);

			this.uploadUrl = upload;
			this.metaList("liudian");
			this.metaList("kctype");
			this.customerListFun();
			if(this.$route.query.id != undefined) {
				this.courseInfo(this.$route.query.id);
			}
		},
		methods: {
			haslicenceImgsRemove(url) {
				this.courseImg.splice(this.courseImg.indexOf(url), 1);
			},
			licenceImgsRemove(file, fileList) {
				this.courseImg.splice(this.courseImg.indexOf(file.response.data), 1);
			},
			licenceImgsPreview(res, file) {
				this.courseImgsUrl = res.data;
				this.courseImg.push(res.data);
			},
			beforeUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isPNG = file.type === 'image/png';
				const isLt1M = file.size / 1024 / 1024 < 1;
				if(!isJPG && !isPNG) {
					this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
				}
				if(!isLt1M) {
					this.$message.error('上传头像图片大小不能超过 1MB!');
				}
				return(isJPG || isPNG) && isLt1M;
			},
			changeValue(value) {
				this.rmb = Number(value * this.ld.value);
			},
			changePer(value) {
				if(this.formData.coursePoints != "") {
					this.per = Number(value / (this.ld.value * this.formData.coursePoints) * 100).toFixed(2);
				}
			},
			addSubTime() {
				if(this.subTime.coursePoint == ""){
					this.subTime.coursePoint = this.formData.coursePoints
				}
				if(this.subTime.maxBabys == ""){
					this.subTime.maxBabys = this.formData.maxBabys
				}
				if(this.subTime.startTime != ""){
					this.subTime.startTime = dtime(this.subTime.startTime.getTime()).format('YYYY-MM-DD HH:mm')
				}
				const date = 
				this.formData.courseTimes.push(this.subTime);
			},
			removeDate(value) {
				this.formData.courseTimes.splice(this.formData.courseTimes.indexOf(value), 1);
			},
			async courseInfo(id) {
				try {
					let userId = this.$store.getters.getUser.userId;
					let userName = this.$store.getters.getUser.username;
					const returnData = await courseInfo({
						id: id,
					});
					if(returnData.code == "0") {
						this.formData = returnData.obj;
						if(returnData.obj.courseImgs != ""){
							this.courseImg = returnData.obj.courseImgs.split(",");
							this.hasLicenceImg = true;
						}
						
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async customerListFun() {
				try {
					let userId = this.$store.getters.getUser.userId;
					let userName = this.$store.getters.getUser.username;
					const returnData = await customerList({
						pageSize: "100",
						pageNum: "1",
						bdId: userName == "admin" ? "" : userId
					});
					if(returnData.code == "0") {
						this.customerList = returnData.list.rows;
					} else {
						this.$message({
							type: 'error',
							message: returnData.msg
						});
					}
				} catch(err) {
					console.log('获取数据失败', err);
				}
			},
			async metaList(type) {
				let _this = this;
				if(type == "kctype") {
					_this.classifyList = []
				} else if(type == "liudian") {
					_this.addressList = []
				}
				const res = await metaList({
					type: type,
					pageSize: "500",
					pageNum: "1",
				});
				if(res.code == "0") {
					if(type == "kctype") {
						_this.classifyList = res.list.rows;
					} else if(type == "liudian") {
						this.ld = res.list.rows[0];
						this.rmb = this.ld.value;
					}
				} else {
					this.$notify.error({
						title: '错误',
						message: res.msg,
						offset: 100
					});
				}
			},
			courseSaveFun(formName) {
				this.$refs[formName].validate(async(valid) => {
					if(valid) {
						let res = null;
						if(this.courseImg.length > 0) {
							this.formData.courseImgs = this.courseImg.join(",");
						}
						if(this.presentItems.length > 0) {
							this.formData.presentItems = this.presentItems.join(",");
						}
						if(this.formData.id != "") {
							res = await courseUpdate(this.formData);
						} else {
							res = await courseSave(this.formData);
						}
						if(res.code == "0") {
							this.$notify({
								title: '成功',
								message: '保存成功',
								type: 'success',
								offset: 100
							});
							this.$router.push({
								path: 'hdList'
							});
						} else {
							this.$notify.error({
								title: '错误',
								message: res.msg,
								offset: 100
							});
						}
					} else {
						this.$notify.error({
							title: '错误',
							message: '请输入正确的用户名密码',
							offset: 100
						});
						return false;
					}
				});
			}

		},
		watch: {
			"formData.courseOwner" (val, oldval) {
				let _this = this;
				this.customerList.forEach(function(item) {
					if(item.id == val) {
						_this.customer.customerAddress = item.customerAddress;
						_this.customer.linkerPhone = item.linkerPhone;
						_this.customer.takePercent = item.takePercent;
						_this.ldRmb = Number(_this.ld.value * item.takePercent / 100);
						let point = new BMap.Point(item.longitude, item.latitude);
						_this.map.centerAndZoom(point, 15);
						let marker = new BMap.Marker(new BMap.Point(item.longitude, item.latitude));
						_this.map.addOverlay(marker);
					}
				});
			},
		}, //以V-model绑定数据时使用的数据变化监测  
	}
</script>

<style scoped>
	.box-card {
		margin: 0 10px;
	}
	
	.title {
		background-color: #20a0ff;
		line-height: 60px;
		font-size: 18px;
		color: #fff;
	}
	
	#allmap {
		height: 300px;
		width: 100%;
	}
	
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: #20a0ff;
	}
	
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	
	.selDate {
		padding: 10px;
		display: block;
		text-align: center;
		margin-top: 20px;
	}
</style>